#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include "Stack.h"

//初始化栈
void StakInit(Stack* ps)
{
    assert(ps);
    ps->arr = NULL;
    ps->capacity = 0;
    ps->top = 0;
}

//入栈
void StackPush(Stack* ps, ElementType element)
{
    assert(ps);
    //判断是否需要扩容
    if(ps->top == ps->capacity)
    {
        int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
        ps->arr = (ElementType*)realloc(ps->arr, newcapacity * sizeof(ElementType));
        if(ps->arr == NULL)
        {
            printf("relloc faik!\n");
            exit(-1);
        }
        ps->capacity = newcapacity;
    }
    ps->arr[ps->top] = element;
    ps->top++;
}

// 出栈，并返回出栈的元素
ElementType StackPop(Stack* ps)
{
    assert(ps);
    if(ps->top <= 0)
    {
        printf("stack is empty!\n");
        exit(-1);
    }
    ps->top--;
    return ps->arr[ps->top];
}

//获取栈顶元素 
ElementType StackTop(Stack* ps)
{
    assert(ps);
    if(ps->top <= 0)
    {
        printf("stack is empty!\n");
    }
    return ps->arr[ps->top - 1];
}

//获取栈中有效元素个数（interesting也可用size_t）
int StackSize(Stack* ps)
{
    assert(ps);
    return ps->top;
}

//检测栈是否为空，如果为空返回非零结果，如果不为空返回零
bool StackEmpty(Stack* ps)
{
    assert(ps);
    return ps->top == 0;
}

//销毁栈
void StackDestroy(Stack* ps)
{
    assert(ps);
    ps->capacity = 0;
    ps->top = 0;
    free(ps->arr);
    ps->arr = NULL;
}

